/***
 * @Description:
 * @Author: LI Yihong
 * @Email: liyh@jihua.ac.cn
 * @Date: 2025-02-27 15:03:09
 * @LastEditTime: 2025-02-27 15:03:17
 * @LastEditors: LI Yihong
 * @FilePath: \STM32F407_AD9910_SPI_CTRL\applications\AD9910\AD9910_Single_Tone.cpp
 */
#include "AD9910_Single_Tone.hpp"

AD9910_Single_Tone::AD9910_Single_Tone()
{
    this->module_init();

    this->sendProfile();
}

AD9910_Single_Tone::AD9910_Single_Tone(const uint64_t freq, const uint16_t Amp)
{
    this->setFreq(freq);
    this->setAmp(Amp);
    this->module_init();

    this->sendProfile();
}

AD9910_Single_Tone::~AD9910_Single_Tone()
{
}

void AD9910_Single_Tone::setDefaultCFR()
{
    CFR1 = {0x00, 0x40, 0x00, 0x00}; // 反Sinc滤波器使能
    CFR2 = {0x01, 0x00, 0x00, 0x00}; // 使能单频profile调制幅度
    CFR3 = {0x05, 0x0F, 0x41, 0x32}; // VC0 = 0b101(VCO5); ICP = 0b001(237uA); 输入分频器正常工作; REFCLK PLL使能; 分频模数 = 0b11001(25倍频); 40MHz输入 * 25倍频 = 1GHz主频
}

/**
 * @brief 设置AD9910输出信号的频率
 *
 * 根据输入频率计算控制字，并将控制字写入profile中。
 *
 * @param freq 输入频率，单位为Hz，范围0~420000000Hz
 */
void AD9910_Single_Tone::setFreq(const uint64_t freq)
{
    // 主频1GHz，32位相位累加器，故每Hz在的控制字增量 delta =  4.294967296 = (2^32)/1000000000
    uint64_t Temp = freq > 420000000 ? 1803886264 : freq * 4.294967296;
    // 将输入频率因子分为四个字节
    profile[7] = (uint8_t)(Temp >> 0) & 0xFF;
    profile[6] = (uint8_t)(Temp >> 8) & 0xFF;
    profile[5] = (uint8_t)(Temp >> 16) & 0xFF;
    profile[4] = (uint8_t)(Temp >> 24) & 0xFF;
}

/**
 * @brief 设置AD9910的幅度
 *
 * 根据输入幅值计算控制字，并将控制字写入profile中。
 *
 * @param Amp 幅度控制字，范围0~16383，控制数据0~16383对应输出幅度0~800mV左右
 */
void AD9910_Single_Tone::setAmp(const uint16_t Amp)
{
    uint16_t temp = Amp > 0x3FFF ? 0x3FFF : Amp;

    profile[0] = (uint8_t)(temp >> 8) & 0xFF;
    profile[1] = (uint8_t)(temp >> 0) & 0xFF;
}

void AD9910_Single_Tone::sendProfile()
{
    spi_sendData(REG_PROFILE_0, profile);
}
